<?php

class MarketController extends AppController {

	var $paginate = array(
		'Market' => array('order' => 'Market.id DESC', 'limit' => 10)
	);

	public function index() {
		$conditions = array();
		$showPersonColumns = 0;	// all
		$actualUser = $this->Session->read('Auth.User');
		if (in_array($actualUser['Person']['fk_person_type_id'], PersonType::getTipsterTypeList())) {
			$tipster = new Person($actualUser['Person']['id']);
			$childrenIdList = array();
			$children = $tipster->getChildren();
			foreach ($children as $child) {
				$childId = intval($child['Person']['id']);
				$childrenIdList[] = $childId;
				$nextLevelTipster = new Person($childId);
				$nextLevelChildren = $nextLevelTipster->getChildren();
				foreach ($nextLevelChildren as $nextLevelChild) {
					$nextChildId = intval($nextLevelChild['Person']['id']);
					$childrenIdList[] = $nextChildId;
				}
			}
			//print_r($childrenIdList);
			$conditions = array('Market.fk_tipster_id' => $childrenIdList);
			$showPersonColumns = 1;
		} elseif (in_array($actualUser['Person']['fk_person_type_id'], array(PersonType::PT_BROKER))) {
			$conditions = array('Market.fk_broker_id' => $actualUser['Person']['id']);
			$showPersonColumns = 2;
		}
		
		// pre maklerov a tiperov vytiahneme vsetky ich provizie
		if ($showPersonColumns !== 0) {
			$this->Commission->recursive = 1;
			$commissions = $this->Commission->find('all', array('conditions' => array('Commission.fk_person_id' => $actualUser['Person']['id'])));
			$myCommissions = array();
			foreach ($commissions as $commission) {
				if (in_array($commission['Commission']['type'], array(1, 2))) {
					$type = Market::MT_OFFER;
					$marketId = $commission['Transfer']['fk_offer_id'];
				} else {
					$type = Market::MT_DEMAND;
					$marketId = $commission['Transfer']['fk_demand_id'];
				}
				
				$myCommissions[$type][$marketId] = $commission['Commission']['value'];
				$this->set('myCommissions', $myCommissions);
			}
		}
		
		$personType = $this->PersonType->read(NULL, intval($actualUser['Person']['fk_person_type_id']));
		$this->set('personType', $personType);
		
		$this->Market->recursive = 0;
		$this->set('markets', $this->paginate($conditions));
		$this->set('showPersonColumns', $showPersonColumns);
	}

	public function view($id = null) {
		$this->Market->id = $id;
		if (!$this->Market->exists()) {
			$this->setFlashError('Záznam nebol nájdený.');
			$this->redirect(array('action' => 'index'));
		}
		$showPersonColumns = TRUE;
		$market = $this->Market->read(null, $id);
		//print_r($market);exit();
		$actualUser = $this->Session->read('Auth.User');
		if (in_array($actualUser['Person']['fk_person_type_id'], PersonType::getTipsterTypeList())) {
			if ($market['Market']['fk_tipster_id'] == $actualUser['Person']['id']) {
				$showPersonColumns = FALSE;
			} else {
				$this->setFlashError('Záznam nebol nájdený.');
				$this->redirect(array('action' => 'index'));
			}
		} elseif (in_array($actualUser['Person']['fk_person_type_id'], array(PersonType::PT_BROKER))) {
			if ($market['Market']['fk_broker_id'] == $actualUser['Person']['id']) {
				$showPersonColumns = 1;
			} else {
				$this->setFlashError('Záznam nebol nájdený.');
				$this->redirect(array('action' => 'index'));
			}
		}
		$this->set('market', $market);
		$this->set('showPersonColumns', $showPersonColumns);
	}

	public function add() {
		if ($this->request->is('post')) {
			$this->Market->create();

			// ak user zmaze commission, posle sa null a to nie je float, takze by to hodilo error
			$this->request->data['Market']['commission'] = floatval($this->request->data['Market']['commission']);
			if ($this->Market->save($this->request->data)) {
				$this->setFlashSuccess('Záznam bol uložený do databázy.');
				$this->redirect(array('action' => 'index'));
			} else {
				$this->setFlashError('Záznam sa nepodarilo uložiť do databázy.');
			}
		}
		$this->getPersonList();
		$this->canShowCommission();
	}

	public function addNew() {
		if ($this->request->is('post')) {

			$canContinue = TRUE;
			// signalizuje ze bol vytvoreny novy klient
			if ($this->request->data['Market']['client_check'] == 1) {
				// nastavime ze novo vytvorena osoba je klient
				$this->request->data['Person']['fk_person_type_id'] = PersonType::PT_CLIENT;
				$this->Person->create();
				if ($this->Person->save($this->request->data['Person'])) {
					// ID novovytvoreneho klienta ulozime ako fk_client_id
					$this->request->data['Market']['fk_client_id'] = $this->Person->id;
				} else {
					$this->setFlashError('Záznam sa nepodarilo uložiť do databázy.');
					$canContinue = FALSE;
				}
			}
			//print_r($this->request->data);exit();
			$this->Market->create();

			// ak user zmaze commission, posle sa null a to nie je float, takze by to hodilo error
			$this->request->data['Market']['commission'] = floatval($this->request->data['Market']['commission']);

			$actualUser = $this->Session->read('Auth.User');
			if ($actualUser['Person']['fk_person_type_id'] == PersonType::PT_BROKER) {
				$this->request->data['Market']['fk_broker_id'] = $actualUser['Person']['id'];
			} elseif (in_array($actualUser['Person']['fk_person_type_id'], PersonType::getTipsterTypeList())
				|| $actualUser['Person']['fk_person_type_id'] == PersonType::PT_ADMIN) {
				$this->request->data['Market']['fk_tipster_id'] = $actualUser['Person']['id'];
			}

			if ($canContinue && $this->Market->save($this->request->data)) {
				$this->setFlashSuccess('Záznam bol uložený do databázy.');
				$this->redirect(array('action' => 'index'));
			} else {
				$this->setFlashError('Záznam sa nepodarilo uložiť do databázy.');
			}
		}
		
		// tiperom a dalsim vybranym typom nebudeme zobrazovat dropdown pre vyber klienta, budu musiet priamo vyplnit udaje o novom
		$loggedUserIsAdmin = TRUE;	// nazov uz nie je uplne vhodny lebo aj typ admin chceli mat ako obycajneho tipera
		$actualUser = $this->Session->read('Auth.User');
		if (in_array($actualUser['Person']['fk_person_type_id'], 
			array(PersonType::PT_BROKER, PersonType::PT_CLIENT, PersonType::PT_F3,
				PersonType::PT_T1, PersonType::PT_T2, PersonType::PT_T3, PersonType::PT_ADMIN))) {
			$loggedUserIsAdmin = FALSE;
		}
		$this->set('loggedUserIsAdmin', $loggedUserIsAdmin);
		$this->getPersonList();
		$this->canShowCommission();
	}

	public function edit($id = null) {
		$this->Market->id = $id;
		if (!$this->Market->exists()) {
			$this->setFlashError('Záznam nebol nájdený.');
			$this->redirect(array('action' => 'index'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->Market->save($this->request->data)) {
				$this->setFlashSuccess('Záznam bol uložený do databázy.');
				$this->redirect(array('action' => 'index'));
			} else {
				$this->setFlashError('Záznam sa nepodarilo uložiť do databázy.');
			}
		} else {
			$market = $this->Market->read(null, $id);
			$this->request->data = $market;
			$actualUser = $this->Session->read('Auth.User');
			if (in_array($actualUser['Person']['fk_person_type_id'], array(PersonType::PT_F3, PersonType::PT_T1, PersonType::PT_T2, PersonType::PT_T3))) {
				if ($market['Market']['fk_tipster_id'] == $actualUser['Person']['id']) {
					$showPersonColumns = FALSE;
				} else {
					$this->setFlashError('Záznam nebol nájdený.');
					$this->redirect(array('action' => 'index'));
				}
			} elseif (in_array($actualUser['Person']['fk_person_type_id'], array(PersonType::PT_BROKER))) {
				if ($market['Market']['fk_broker_id'] == $actualUser['Person']['id']) {
					$showPersonColumns = FALSE;
				} else {
					$this->setFlashError('Záznam nebol nájdený.');
					$this->redirect(array('action' => 'index'));
				}
			}
		}
		$this->getPersonList();
		$this->canShowCommission();
	}

	protected function getPersonList() {
		$personList = $this->Person->find('all');

		$clientList = array(
			0 => 'Vyberte klienta'
		);
		$tipsterList = array(
			0 => 'Vyberte tipera'
		);
		$brokerList = array(
			0 => 'Vyberte makléra'
		);
		foreach ($personList as $person) {
			if (in_array($person['PersonType']['id'], array(PersonType::PT_CLIENT))) {
				$clientList[$person['Person']['id']] = $person['Person']['full_name'];
			} elseif (in_array($person['PersonType']['id'], array(PersonType::PT_T1, PersonType::PT_T2, PersonType::PT_T3, PersonType::PT_F3, PersonType::PT_ADMIN))) {
				$tipsterList[$person['Person']['id']] = $person['Person']['full_name'];
			} elseif (in_array($person['PersonType']['id'], array(PersonType::PT_BROKER))) {
				$brokerList[$person['Person']['id']] = $person['Person']['full_name'];
			}
		}
		$this->set('clientList', $clientList);
		$this->set('tipsterList', $tipsterList);
		$this->set('brokerList', $brokerList);
	}

	protected function canShowCommission() {
		$canShowCommission = FALSE;
		$actualUser = $this->Session->read('Auth.User');
		if (in_array($actualUser['Person']['fk_person_type_id'],
				array(PersonType::PT_ASSISTANT, PersonType::PT_ADMIN, PersonType::PT_SUPERADMIN, PersonType::PT_BROKER))) {
			$canShowCommission = TRUE;
		}
		$this->set('canShowCommission', $canShowCommission);
	}
	
	public function delete($id = null) {
		$this->Market->id = $id;
		if (!$this->Market->exists()) {
			$this->setFlashError('Záznam nebol nájdený.');
		} else {
			if ($this->Market->delete()) {
				$this->setFlashSuccess('Záznam bol zmazaný z databázy.');
			} else {
				$errors = array_merge(array('Záznam nebol zmazaný z databázy.'), Errors::getErrors());
				$message = implode("<br />", $errors);
				$this->setFlashError($message);
			}
		}
		$this->redirect(array('action' => 'index'));
	}
	
	public function commission() {
		$actualUser = $this->Session->read('Auth.User');

		$this->Commission->recursive = 1;
		$commissions = $this->Commission->find('all', array('conditions' => array('Commission.fk_person_id' => $actualUser['Person']['id'])));
		$myCommissions = array();
		$myMarketIds = array();
		$totalCommissionValue = 0;
		foreach ($commissions as $commission) {
			// odmena pre maklerov - 1 a pre ponukacov - 2
			if (in_array($commission['Commission']['type'], array(1, 2))) {
				$type = Market::MT_OFFER;
				$marketId = $commission['Transfer']['fk_offer_id'];
			} else {
				$type = Market::MT_DEMAND;
				$marketId = $commission['Transfer']['fk_demand_id'];
			}
			$myMarketIds[] = $marketId;
			$value = $commission['Commission']['value'];
			$myCommissions[$type][$marketId] = $value;
			$totalCommissionValue += $value;
			$this->set('myCommissions', $myCommissions);
		}
		$markets = array();
		if (!empty($myMarketIds)) {
			$conditions = array('Market.status' => Market::STATUS_FINISHED_SUCCESSFULLY, 'Market.id' => $myMarketIds);

			$this->Market->recursive = 0;
			$markets = $this->Market->find('all' , array('conditions' => $conditions, 'order' => 'Market.id DESC'));
		}
		$this->set('markets', $markets);
		$this->set('totalCommissionValue', $totalCommissionValue);
	}
}

?>